package org.jeecg.modules.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.boot.starter.rabbitmq.client.RabbitMqClient;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.base.BaseMap;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.entity.TigDevice;
import org.jeecg.modules.entity.TigDeviceAlarm;
import org.jeecg.modules.entity.TigProduct;
import org.jeecg.modules.service.DeviceService;
import org.jeecg.modules.service.ITigDeviceService;
import org.jeecg.modules.service.ITigProductService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.util.CommonDeviceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 设备
 * @Author: jeecg-boot
 * @Date:   2022-03-09
 * @Version: V1.0
 */
@Api(tags="设备")
@RestController
@RequestMapping("/tiger/tigDevice")
@Slf4j
public class TigDeviceController extends JeecgController<TigDevice, ITigDeviceService> {
	@Autowired
	private ITigDeviceService tigDeviceService;

	@Autowired
	private DeviceService deviceService;

	@Autowired
	private CommonDeviceUtil commonDeviceUtil;

	@Autowired
	private ITigProductService iTigProductService;

	 @Autowired
	 RedisUtil redisUtil;


	 @Autowired
	 private RabbitMqClient rabbitMqClient;

	/**
	 * 分页列表查询
	 *
	 * @param tigDevice
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "设备-分页列表查询")
	@ApiOperation(value="设备-分页列表查询", notes="设备-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TigDevice>> queryPageList(TigDevice tigDevice,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  HttpServletRequest req) {
		QueryWrapper<TigDevice> queryWrapper = QueryGenerator.initQueryWrapper(tigDevice, req.getParameterMap());
		Page<TigDevice> page = new Page<TigDevice>(pageNo, pageSize);
		IPage<TigDevice> pageList = tigDeviceService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 /**
	  * 分页列表查询;
	  *
	  * @param tigDevice
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "设备-分页列表查询")
	 @ApiOperation("设备短信息-分页列表查询")
	 @GetMapping(value = "/shortList")
	 public Result<IPage<TigDevice>> queryShortPageList(TigDevice tigDevice,
												   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												   HttpServletRequest req) {
		 QueryWrapper<TigDevice> queryWrapper = QueryGenerator.initQueryWrapper(tigDevice, req.getParameterMap());
		 queryWrapper.select("id,name,on_status,ison,product_id,ip_addr");
		 Page<TigDevice> page = new Page<TigDevice>(pageNo, pageSize);
		 IPage<TigDevice> pageList = tigDeviceService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 /**
	  * 报警分页列表查询
	  *
	  * @param tigDevice
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "设备-分页列表查询")
	 @ApiOperation(value="设备报警-分页列表查询", notes="设备报警-分页列表查询")
	 @GetMapping(value = "/alarmList")
	 public Result<Page<TigDeviceAlarm>> queryPageAlarmList(TigDevice tigDevice,
												   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												   HttpServletRequest req) {
		 QueryWrapper<TigDevice> queryWrapper = QueryGenerator.initQueryWrapper(tigDevice, req.getParameterMap());
		 Page<TigDevice> page = new Page<TigDevice>(pageNo, pageSize);
		 IPage<TigDevice> pageList = tigDeviceService.page(page, queryWrapper);
		 List<TigDeviceAlarm> list = new ArrayList<>();
		 Page<TigDeviceAlarm> retPage = new Page<TigDeviceAlarm>(pageNo, pageSize);
		 //组装报警数据实体类
		 for (int i = 0; i < pageList.getRecords().size(); i++) {
			 TigDevice dev = pageList.getRecords().get(i);
			 TigDeviceAlarm devAlarm = new TigDeviceAlarm();
			 devAlarm.setId(dev.getId());
			 devAlarm.setName(dev.getName());
			 devAlarm.setSysOrgCode(dev.getSysOrgCode());
			 devAlarm.setIpAddr(dev.getIpAddr());
			 devAlarm.setPort(dev.getPort());
			 devAlarm.setOnStatus(dev.getOnStatus());
			 devAlarm.setShadowName(dev.getShadowName());

			 devAlarm.setCityWarnCount(redisUtil.get("device_warning_1type" + dev.getId()) != null ? Integer.parseInt(String.valueOf(redisUtil.get("device_warning_1type" + dev.getId()))) : 0);
			 devAlarm.setMainVolWarnCount(redisUtil.get("device_warning_2type" + dev.getId()) != null ? Integer.parseInt(String.valueOf(redisUtil.get("device_warning_2type" + dev.getId()))) : 0);
			 devAlarm.setBakVolWarnCount(redisUtil.get("device_warning_3type" + dev.getId()) != null ? Integer.parseInt(String.valueOf(redisUtil.get("device_warning_3type" + dev.getId()))) : 0);
			 devAlarm.setCurWarnCount(redisUtil.get("device_warning_4type" + dev.getId()) != null ? Integer.parseInt(String.valueOf(redisUtil.get("device_warning_4type" + dev.getId()))) : 0);
			 devAlarm.setTempWarnCount(redisUtil.get("device_warning_5type" + dev.getId()) != null ? Integer.parseInt(String.valueOf(redisUtil.get("device_warning_5type" + dev.getId()))) : 0);
			 devAlarm.setUpsWarnCount(redisUtil.get("device_warning_6type" + dev.getId()) != null ? Integer.parseInt(String.valueOf(redisUtil.get("device_warning_6type" + dev.getId()))) : 0);
			 devAlarm.setOtherWarnCount(redisUtil.get("device_warning_7type" + dev.getId()) != null ? Integer.parseInt(String.valueOf(redisUtil.get("device_warning_7type" + dev.getId()))) : 0);
			 devAlarm.setStrWarnData(redisUtil.get("device_warning_time" + dev.getId()) != null ? String.valueOf(redisUtil.get("device_warning_time" + dev.getId())) : "");
			 list.add(devAlarm);
		 }
		 retPage.setRecords(list);
		 retPage.setCurrent(pageList.getCurrent());
		 retPage.setTotal(pageList.getTotal());
		 return Result.OK(retPage);
	 }
	
	/**
	 *   添加
	 *
	 * @param tigDevice
	 * @return
	 */
	@AutoLog(value = "设备-添加")
	@ApiOperation(value="设备-添加", notes="设备-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TigDevice tigDevice) throws Exception {
		if(deviceService.isExistSameDevice(tigDevice)){
			return Result.error("添加失败！检测到设备名或者IP和端口存在冲突");
		}
		TigProduct p = iTigProductService.getById(tigDevice.getProductId());
		tigDevice.setShadowName(p.getModelDesc());
		tigDeviceService.save(tigDevice);
		deviceService.reloadDevice(tigDevice.getId());
		deviceService.generateDeviceOperateLog(tigDevice.getId(),"201","添加了设备:【" + tigDevice.getName() + "】");
		commonDeviceUtil.connectDevice(tigDevice.getId());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param tigDevice
	 * @return
	 */
	@AutoLog(value = "设备-编辑")
	@ApiOperation(value="设备-编辑", notes="设备-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody TigDevice tigDevice) throws Exception {
		if(deviceService.isExistSameDevice(tigDevice)){
			return Result.error("修改失败！检测到设备名或者IP和端口存在冲突");
		}
		deviceService.saveBaseDeviceLog(tigDevice);
		tigDeviceService.updateById(tigDevice);
		deviceService.reloadDevice(tigDevice.getId());
		deviceService.saveDevice(deviceService.getDevice(tigDevice.getId()));
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "设备-通过id删除")
	@ApiOperation(value="设备-通过id删除", notes="设备-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) throws Exception {
		//deviceService.getTigDevice(id).getName();//断开的设备通过这个实体类会获取不到名字，因为已经移除了
		String name = deviceService.getDevice(id).getShadow().getJSONObject("baseinfo").getString("name");
		deviceService.generateDeviceOperateLog(id,"202","删除了设备:【" + name + "】");
		deviceService.removeDevice(id);
		tigDeviceService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "设备-批量删除")
	@ApiOperation(value="设备-批量删除", notes="设备-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) throws Exception {
		List<String> listIds =  Arrays.asList(ids.split(","));
		for(String id:listIds){
			String name = deviceService.getDevice(id).getShadow().getJSONObject("baseinfo").getString("name");
			deviceService.generateDeviceOperateLog(id,"202","删除了设备:【" + name + "】");
			deviceService.removeDevice(id);
		}
		this.tigDeviceService.removeByIds(Arrays.asList(ids.split(",")));

		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "设备-通过id查询")
	@ApiOperation(value="设备-通过id查询", notes="设备-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TigDevice> queryById(@RequestParam(name="id",required=true) String id) {
		TigDevice tigDevice = tigDeviceService.getById(id);
		if(tigDevice==null) {
			return Result.error("未找到对应数据",null);
		}
		return Result.OK(tigDevice);
	}

	 /**
	  * 通过orgCode查询
	  *
	  * @param org_code
	  * @return
	  */
	 //@AutoLog(value = "通过orgCode查询是否存在设备")
	 @ApiOperation(value="通过orgCode查询是否存在设备", notes="通过orgCode查询是否存在设备")
	 @GetMapping(value = "/queryIsExistDevicesByOrgCode")
	 public Result<TigDevice> queryIsExistDevicesByOrgCode(@RequestParam(name="orgcode",required=true) String org_code) {
		 if(deviceService.isExistDevicesByOrgCode(org_code)){
		 	return Result.OK();
		 }
		 else {
			 return Result.error(null);
		 }
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param tigDevice
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TigDevice tigDevice) {
        return super.exportXls(request, tigDevice, TigDevice.class, "设备");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		Result<?> ret = super.importExcel(request, response, TigDevice.class);
		//连接原在线设备
		List<TigDevice> tigDevices = deviceService.getDevices();
		for (TigDevice tigDevice : tigDevices) {
			deviceService.login(tigDevice.getId(),false);
		}
		return ret;
	}

}
